#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <poll.h>

int main() {
    struct pollfd fds[1];
    int timeout_ms = 5000;  // 超时时间5秒
    
    // 监听标准输入的可读事件和错误事件
    fds[0].fd = STDIN_FILENO;
    fds[0].events = POLLIN | POLLERR ;  // 关注可读和错误事件
    
    printf("Waiting for input or error for 5 seconds...\n");
    char buf[256]="";
    while(1){
        // int ret = poll(fds, 1, timeout_ms);
        int ret = poll(fds, 1, -1);
        if (ret < 0) {
            perror("poll failed");
            return 1;
        } else if (ret == 0) {
            printf("Timeout occurred\n");
            return 0;
        }
        
        // 检查返回的事件
        if (fds[0].revents & POLLIN) {
            printf("Data is available to read\n");
            ssize_t len = read(fds[0].fd, buf, 256);
            printf("%ld---->%s",len, buf);
            bzero(buf, 256); // 清空
        }  
        
        if (fds[0].revents & POLLERR) {
            printf("An error occurred on the file descriptor\n");
            // 处理错误...
            break;
        }
        
        if (fds[0].revents & POLLHUP) {
            printf("File descriptor was hung up\n");
            // 处理挂起...
            break;
        }
    }
    return 0;
}